package servlet;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pojo.Cargo;
import service.CargoManager;
import service.WarehouseManager;
import service.factory.ManagerFactory;
import verify.MyVerify;

/**
 * Servlet implementation class CommitOrder
 */
@WebServlet("/cargo/commit")
public class CommitCargo extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private CargoManager cargoManager;
	private WarehouseManager warehouseManager;
	private MyVerify myVerify;
	
    public CommitCargo() {
        super();
        cargoManager = ManagerFactory.getCargoManagerInstance();
        warehouseManager = ManagerFactory.getWarehouseManagerInstance();
        myVerify = new MyVerify();
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String cw_id = request.getParameter("w_id");
		String ccname = request.getParameter("cname");
		String cprice = request.getParameter("price");
		String ccnumber = request.getParameter("cnumber");
		boolean isError = false;
		if (!(cw_id!=null&&warehouseManager.getWarehouse(cw_id)!=null)) {
			isError = false;
			request.setAttribute("ew_id","wrong warehouse" );
		}
		if (!(ccname!=null&&ccname.length()>3&&ccname.length()<20)) {
			isError = true;
			request.setAttribute("ecname", "wrong name");
		}
		if (!myVerify.verifyDouble(cprice).equals(MyVerify.SUCCESS)) {
			isError = true;
			request.setAttribute("eprice", "wrong price");
		}
		if (!myVerify.verifyInteger(ccnumber).equals(MyVerify.SUCCESS)) {
			isError = true;
			request.setAttribute("enumber", "wrong number");
		}
		if (isError) {
			request.setAttribute("w_id", cw_id);
			request.setAttribute("cname", cprice);
			request.setAttribute("price", cprice);
			request.setAttribute("cnumber", ccnumber);
			request.getRequestDispatcher("add").forward(request, response);
			return;
		}
		
		double price = Double.parseDouble(cprice);
		Integer cnumber = Integer.parseInt(ccnumber);
		Cargo cargo = new Cargo(null,ccname,cnumber,price,new Date(),cw_id);
		int m = cargoManager.add(cargo);
		if (m>0) {
			response.sendRedirect("cargo?w_id="+cw_id);
		}else{
			request.setAttribute("w_id", cw_id);
			request.setAttribute("cname", cprice);
			request.setAttribute("price", cprice);
			request.setAttribute("cnumber", ccnumber);
			request.setAttribute("info", "insert fail");
			request.getRequestDispatcher("add").forward(request, response);
			return;
		}
	}

}
